﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace PIT.Labs.ProjectRepository.Owl2DotNet.Parsers
{
    /// <summary>
    /// Base implemenatation of <see cref="T:owl2DotNet.Ontology.Parsers.IOntologyParser"/> to be used by further implementations
    /// </summary>
    public abstract class OntologyParserBase : IOntologyParser
    {
        /// <summary>
        /// Opens the file as a stream and passes the stream to <see cref="Load(Stream)"/>
        /// </summary>
        /// <param name="filename">Path to the file that shall be opened</param>
        /// <returns>Parsed ontology</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1057:StringUriOverloadsCallSystemUriOverloads")]
        public virtual IOntology Load(string filename)
        {
            using (Stream strm = File.OpenRead(filename))
            {
                return ParseOntologyFromStream(strm);
            }
        }

        /// <summary>
        /// Opens the URI as a stream and passes the stream to <see cref="Load(Stream)"/>
        /// </summary>
        /// <param name="uri">URI from which the ontology will be retrieved</param>
        /// <returns>Parsed ontology</returns>
        public virtual IOntology Load(Uri uri)
        {
            using (WebClient wc = new WebClient())
            {
                using (Stream strm = wc.OpenRead(uri))
                {
                    return ParseOntologyFromStream(strm);
                }
            }
        }

        private IOntology ParseOntologyFromStream(Stream strm)
        {
            IOntology o = Load(strm);
            return o;
        }

        /// <summary>
        /// Needs to be implemented to pase an ontology from a stream.
        /// </summary>
        /// <param name="instream">stream from wich the ontology can be read</param>
        /// <returns>Parsed ontology</returns>
        public abstract IOntology Load(Stream instream);
    }
}
